/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lindenvalley.de.achartengine;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.tools.PanListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.lindenvalley.de.R;
import com.lindenvalley.de.content.Section;
import com.lindenvalley.de.content.Sections;
import com.lindenvalley.de.database.DbSectionsHelper;
import com.lindenvalley.de.network.WorkServer;

public class XYChartBuilder extends Activity {
  public static final String TYPE = "type";

  private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();

  private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

  private XYSeries mCurrentSeries;

  private XYSeriesRenderer mCurrentRenderer;

  private String mDateFormat;

  private GraphicalView mChartView;
  
  private Sections sections;
  private Section currentSection;
  private DbSectionsHelper sectionsHelper;
  private SQLiteDatabase readDatabase;
  private String[] columns = new String[]{DbSectionsHelper.ROUND, "(select count(*) from section s2 where answer_type=1 and s1.theme_id=s2.theme_id and s1.round=s2.round)"};
  private int isExamMode;
  private TextSwitcher leanView, examView;
  private TextView themeNameView;
  

  @Override
  protected void onRestoreInstanceState(Bundle savedState) {
    super.onRestoreInstanceState(savedState);
    mDataset = (XYMultipleSeriesDataset) savedState.getSerializable("dataset");
    mRenderer = (XYMultipleSeriesRenderer) savedState.getSerializable("renderer");
    mCurrentSeries = (XYSeries) savedState.getSerializable("current_series");
    mCurrentRenderer = (XYSeriesRenderer) savedState.getSerializable("current_renderer");
    mDateFormat = savedState.getString("date_format");
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("dataset", mDataset);
    outState.putSerializable("renderer", mRenderer);
    outState.putSerializable("current_series", mCurrentSeries);
    outState.putSerializable("current_renderer", mCurrentRenderer);
    outState.putString("date_format", mDateFormat);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stat);
    
    leanView = (TextSwitcher) findViewById(R.id.statViewLearn);
    examView = (TextSwitcher) findViewById(R.id.statViewExam);
    themeNameView = (TextView) findViewById(R.id.statViewTheme);
    MyTouchListener listener = new MyTouchListener();
    leanView.setOnTouchListener(listener);
    examView.setOnTouchListener(listener);
    themeNameView.setOnTouchListener(listener);
    
    mRenderer.setGridColor(Color.BLACK);
    mRenderer.setApplyBackgroundColor(true);
    mRenderer.setBackgroundColor(Color.WHITE);
    mRenderer.setAxisTitleTextSize(16);
    mRenderer.setChartTitleTextSize(20);
    mRenderer.setLabelsTextSize(15*1.3f);
    mRenderer.setLabelsColor(Color.WHITE);
//    mRenderer.setChartValuesTextSize(15*1.3f);
    mRenderer.setLegendHeight(0);
    mRenderer.setLegendTextSize(0);
    mRenderer.setShowLegend(false);
    mRenderer.setInScroll(false);
    mRenderer.setYAxisMin(0);
    mRenderer.setYAxisMax(100);    
    
    mRenderer.setMargins(new int[] { 0, 0, 0, 0 });
    mRenderer.setZoomButtonsVisible(false);
    mRenderer.setPointSize(1);
    
    
    sections = WorkServer.getInstance().getSections();
	if (sections != null && !sections.getSection().isEmpty()){
		currentSection = sections.getSection().get(0);
	}
	sectionsHelper = new DbSectionsHelper(this);
	readDatabase = sectionsHelper.getReadableDatabase();
	
	mCurrentSeries = new XYSeries("");
    mDataset.addSeries(mCurrentSeries);
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);
    renderer.setPointStyle(PointStyle.CIRCLE);
    renderer.setFillPoints(true);    
    renderer.setColor(getResources().getColor(R.color.colorAnswerGreen));
    renderer.setChartValuesTextSize(15*1.3f);
    mCurrentRenderer = renderer;
    mCurrentRenderer.setFillBelowLine(true);
    mCurrentRenderer.setFillBelowLineColor(Color.GREEN);
    mCurrentRenderer.setDisplayChartValues(true);
//    mCurrentRenderer.setDisplayChartValues(true);
  }
  


/* (non-Javadoc)
 * @see android.app.Activity#onCreateDialog(int)
 */
@Override
protected Dialog onCreateDialog(int id) {
	AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
	CharSequence[] items = new CharSequence[sections.getSection().size()];
	for (int i = 0; i < items.length; i++){
		items[i] = sections.getSection().get(i).getName();
	}
	alertDialog.setItems(items, new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			currentSection = sections.getSection().get(which);
			getChartsSeries();
			mChartView.repaint();
		}
	});
	return alertDialog.create();

	
}

private void getChartsSeries(){
		Cursor cursor = readDatabase.query(
				DbSectionsHelper.TABLE_NAME + " s1", 
				columns, 
				DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.IS_EXAM + "=?" , 
				new  String[]{String.valueOf(currentSection.getId()), String.valueOf(isExamMode)}, 
				DbSectionsHelper.ROUND, null, DbSectionsHelper.ROUND);
		int dataCount = cursor.getCount();
		mCurrentSeries.setTitle(currentSection.getName());
		mCurrentSeries.clear();
		int questionsSize = currentSection.getQuestion().size();
		if (dataCount > 0){		
			cursor.moveToFirst();
			int round, questions;
			do{
				round = cursor.getInt(0);
				questions = cursor.getInt(1);
				questions = questions *100 /questionsSize;
//				Log.i(getClass().getSimpleName(), "round " + round + ", question " + questions);
				mCurrentSeries.add(round, questions);				
			} while (cursor.moveToNext());
		}
		cursor.close();
		themeNameView.setText(currentSection.getName());
	  
  }

  @Override
  protected void onResume() {
    super.onResume();
    getChartsSeries();
    if (mChartView == null) {
      LinearLayout layout = (LinearLayout) findViewById(R.id.statLinearLayout);
      mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
      mChartView.setBackgroundColor(Color.MAGENTA);
      mRenderer.setClickEnabled(true);
      mRenderer.setSelectableBuffer(100);
      mChartView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
          double[] xy = mChartView.toRealPoint(0);
          if (seriesSelection == null) {
            Toast.makeText(XYChartBuilder.this, "No chart element was clicked", Toast.LENGTH_SHORT)
                .show();
          } else {
            Toast.makeText(
                XYChartBuilder.this,
                "Chart element in series index " + seriesSelection.getSeriesIndex()
                    + " data point index " + seriesSelection.getPointIndex() + " was clicked"
                    + " closest point value X=" + seriesSelection.getXValue() + ", Y=" + seriesSelection.getValue()
                    + " clicked point value X=" + (float) xy[0] + ", Y=" + (float) xy[1], Toast.LENGTH_SHORT).show();
          }
        }
      });
      mChartView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
          SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
          if (seriesSelection == null) {
            Toast.makeText(XYChartBuilder.this, "No chart element was long pressed",
                Toast.LENGTH_SHORT);
            return false; // no chart element was long pressed, so let something
            // else handle the event
          } else {
            Toast.makeText(XYChartBuilder.this, "Chart element in series index "
                + seriesSelection.getSeriesIndex() + " data point index "
                + seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
            return true; // the element was long pressed - the event has been
            // handled
          }
        }
      });
      mChartView.addPanListener(new PanListener() {
        public void panApplied() {
          System.out.println("New X range=[" + mRenderer.getXAxisMin() + ", " + mRenderer.getXAxisMax()
              + "], Y range=[" + mRenderer.getYAxisMax() + ", " + mRenderer.getYAxisMax() + "]");
        }
      });
      layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
          LayoutParams.FILL_PARENT));
    } else {
      mChartView.repaint();
    }
  }
  
  class MyTouchListener implements View.OnTouchListener{

		/* (non-Javadoc)
		 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
		 */
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			int id = v.getId();
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				switch (id) {
				case R.id.statViewLearn:
					if (isExamMode == 1){
						isExamMode = 0;
						leanView.showNext();
						examView.showNext();
					}
					
					break;
				case R.id.statViewExam:
					if (isExamMode == 0){
						isExamMode = 1;
						leanView.showNext();
						examView.showNext();
					}
					break;
					
				case R.id.statViewTheme:
					showDialog(1);
				
				}
				getChartsSeries();
				mChartView.repaint();
				return true;
			} else
				return false;
		}
		
	}

}
